package com.ushine.web.config.duird;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 配置主数据源
 * 将配置类注入到bean容器，使ConfigurationProperties注解类生效
 *
 * @author yls
 * @Date 2019年10月12日
 */
@Configuration
@Slf4j
@EnableConfigurationProperties({DataSourceProperties.class, DataSourceCommonProperties.class})
public class PrimaryDruidDataSourceConfig {

    @Resource
    private DataSourceProperties dataSourceProperties;

    @Resource
    private DataSourceCommonProperties dataSourceCommonProperties;


    @Primary
    @Bean("primaryDruidDataSource")
    @Qualifier("primaryDruidDataSource")
    public DataSource primaryDruidDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        //配置数据源属性
        datasource.setUrl(dataSourceProperties.getPrimary().get("url"));
        datasource.setUsername(dataSourceProperties.getPrimary().get("username"));
        datasource.setPassword(dataSourceProperties.getPrimary().get("password"));
        datasource.setDbType(dataSourceProperties.getPrimary().get("db-type"));
        datasource.setDriverClassName(dataSourceProperties.getPrimary().get("driver-class-name"));

        // 统一配置项
        dataSourceCommonProperties.getCommonProperties(datasource);
        return datasource;
    }

}